﻿@using si.caha.Helper;

@{
    // Set the layout page and page title
    Layout = "~/tpl/_layout.cshtml";
    PageData["PageTitle"] = "Forget Your Password?";

    bool passwordSent = false;
    var emailError = "";
    var disabledAttribute = "";
    var email = Request.Form["email"];

    if (IsPost) 
    {
        // validate email
        if (email.IsEmpty() || !Validator.IsEmailValid(email)) 
        {
            emailError = "Please enter a valid email";
        }
        else 
        {
            if (WebSecurity.GetUserId(email) > -1 && WebSecurity.IsConfirmed(email)) 
            {
                var resetToken = WebSecurity.GeneratePasswordResetToken(email);
                
                var portPart = "";
                var port = Request.Url.Port;
                if (port != 80) 
                {
                    portPart = ":" + port;
                }
                var resetUrl = Request.Url.Scheme + "://" + 
                            Request.Url.Host + 
                            portPart + 
                            VirtualPathUtility.ToAbsolute("~/Account/PasswordReset?resetToken=" + Url.Encode(resetToken));
                
                Mail.Send(
                    to: email,	
                    subject: "Please reset your password", 
                    body: "Use this password reset token to reset your password. The token is: " 
                    + resetToken + @". Visit <a href=""" + resetUrl + @""">" + resetUrl + "</a> to reset your password."
                );
            }
            
            passwordSent = true; // We don't want to disclose that the user does not exist.
            disabledAttribute = "disabled";
        }
    }
}

<fieldset>
    <legend>Password Reset Instructions Form</legend>
    <p>
        We will send password reset instructions to the email address associated with your account. 
    </p>
    <form method="post" action="">
        @if (passwordSent) 
        {
            <div>
                Instructions to reset your password have been sent to the specified email address.
            </div>
        }
        <div>
            <label for="email">Email Address</label>
            <input type="email" name="email" value="@email" @disabledAttribute/>
            @if (!emailError.IsEmpty()) 
            {
                <span>@emailError</span>
            }
        </div>
        <div>
            <input type="submit" value="Send Instructions" @disabledAttribute/>
        </div>
    </form>
</fieldset>
